// TODO: FIX INGORE
//@ts-ignore
import JSEncrypt from 'jsencrypt';
import * as CONSTANT from './constant';

/**
 * 获取URL中的某参数值,不区分大小写
 * @param {String} name 参数名称
 */
export function getQueryString(name: string) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  const r = window.location.search.substr(1).match(reg);
  if (r !== null) {
    return unescape(r[2]);
  }
  return '';
}

/**
 * 处理价格保留
 */
export const handlePrice = (params: any) => {
  if (typeof params.value !== 'number') return params.value;
  let res = params.value;
  if (!params.ignoreLessZero) {
    res = params.value < 0 ? 0 : params.value;
  }
  return res.toFixed(2);
};

/**
 * 公钥 加密
 */
export const fnencrypt = (param: any) => {
  const enc = new JSEncrypt();
  enc.setPublicKey(CONSTANT.KEYS.pub);
  const reslt = enc.encrypt(param);
  return reslt;
};

/**
 * 私钥 解密
 */
export const fndecrypt = (param: string) => {
  var dec = new JSEncrypt();
  dec.setPrivateKey(CONSTANT.KEYS.priv);
  var reslt = dec.decrypt(param);
  return reslt;
};

/**
 * 过滤掉对象中不需要的属性
 */
export function omit(obj: any, fields: any[]) {
  const reslt = {
    ...obj
  };
  for (let i = 0; i < fields.length; i++) {
    const key = fields[i];
    delete reslt[key];
  }
  return reslt;
}

/**
 * 前端校验
 */
export const VALIDATES = {
  phone: {
    reg: /^1[3456789]\d{9}$/,
    empty: '请填写手机号码',
    error: '请填写11位正确的手机号码'
  },
  name: {
    reg: /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,25}$/,
    empty: '请填写机主姓名',
    error: '机主姓名限2~25位中文字符，请重新填写'
  },
  idCard: {
    reg: /^\d{15}$|(^\d{17}([0-9]|X)$)/,
    empty: '请填写身份证号',
    error: '请正确填写15位或18位身份证号码'
  },
  code: {
    reg: /^\d{6}$/,
    empty: '请填写验证码',
    error: '请填写6位正确的验证码'
  }
};

/**
 * 前端校验 统一函数
 * who 校验什么  value 值
 */
export const validateFactry = (who: string, value: string) => {
  let chk = VALIDATES[who];
  if (!value) {
    return chk.empty;
  } else {
    if (!chk.reg.test(value)) {
      return chk.error;
    }
  }
  return '';
};

// app 新开webview
export function webviewRedirect(url: string) {
  var newUrl = url.replace(/http*:/, '');
  var agent = navigator.userAgent.toLowerCase();
  if (!url) {
    return false;
  }
  if (agent.indexOf('jdapp') >= 0) {
    // 京东内
    let href =
      'openApp.jdMobile://virtual?params={"category":"jump","des":"m","action":"to","url":"' +
      encodeURIComponent(window.location.protocol + newUrl) +
      '"}';
    window.location.href = href;
    return true;
  } else {
    window.location.href = newUrl;
    return true;
  }
}

// 判断wq环境
export const isWXSQ = () => {
  return /AND_SQ|IPH_SQ|micromessenger(\/[\d.]+)*/i.test(navigator.userAgent);
};

//fixmask
export const closest = (el: any, selector: string) => {
  const matchesSelector =
    el.matches ||
    el.webkitMatchesSelector ||
    el.mozMatchesSelector ||
    el.msMatchesSelector;

  while (el) {
    if (matchesSelector.call(el, selector)) {
      return el;
    } else {
      el = el.parentElement;
    }
  }
  return null;
};

/**
 * 姓名，2~25个中文字符
 *
 */
export const checkCardName = (value: string) =>
  /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,25}$/.test(value);

const JSSDK = window['JSSDK'];
export const isJDAPP = JSSDK.Client.isJDApp();

export const loadScript = async (src: string) => {
  return await new Promise<boolean>((resolve, reject) => {
    var script = document.createElement('script'),
      head = document.getElementsByTagName('head')[0];
    script.type = 'text/javascript';
    script.src = src;
    script.addEventListener(
      'load',
      () => {
        resolve(true);
      },
      false
    );
    script.addEventListener('error', err => {
      resolve(false);
    });
    head.appendChild(script);
  });
};

//时间戳转时间  年/月/日
export const dateFormate = (times: any) => {
  let date = new Date(times);
  var Y = date.getFullYear();
  var M =
    date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1;
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

  return Y + '年' + M + '月' + D + '日';
};

export const videoText = (certNameEnc: any, times: any, phone: any) => {
  let norText =
    '我是**瑞，今天是XX年XX月XX日，138****6556是我办理的手机号码，本人承诺依法合规使用，知晓电话卡涉诈的法律风险。';
  let dateText = times ? dateFormate(times) : '';

  if (!dateText || !certNameEnc || !phone) {
    return norText;
  }
  let showText = `我是${certNameEnc}，今天是${dateText}，${phone}是我办理的手机号码，本人承诺依法合规使用，知晓电话卡涉诈的法律风险。`;
  return showText;
};

// 判断ios android环境
export const isAndroidIos = () => {
  let u = navigator.userAgent,
    isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  // isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; // 安卓终端
  return isIos ? true : false;
};
